//
//  YHNetworkTools.swift
//  YHWeibo
//
//  Created by yuhao.mac on 16/6/26.
//  Copyright © 2016年 yuhao.mac. All rights reserved.
//

import UIKit
import AFNetworking

enum MethodType:String {
    case GET = "GET"
    case POST = "POST"
}

class YHNetworkTools: AFHTTPSessionManager {
    //全局访问点
    static let sharedTools:YHNetworkTools = {
        
        let tools = YHNetworkTools()
        //增加格式的支持
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    func requset(method:MethodType, urlString:String, parameters:AnyObject?,success: (response:AnyObject?) -> (), failure: (error:NSError) -> ()){
        
        //GET请求
        if method == MethodType.GET{
            self.GET(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error:err)
            })
        }else{
            self.POST(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                    success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
            })
        }
    }
    
}


extension YHNetworkTools{

    //请求token
    func request(method:MethodType, urlString: String, parameters: AnyObject?, success: (response: AnyObject?)->(), failure: (error: NSError)->()){
        // GET 请求
        if method == .GET {
            self.GET(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
                    
            })
        }else {
            // POST 请求
            self.POST(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
                    
            })
        }
    }
    
    // 请求token
    func oauthLoadUserAccount(code: String, success: (response: AnyObject?)->(), failure: (error: NSError)->()){
        // 请求url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let params = [
            "client_id":APPKEY,
            "client_secret":APPSECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":REDIRECT_URI
        ]
        
        self.request(MethodType.POST, urlString: urlString, parameters: params, success: success, failure: failure)
    }
    
    //请求个人信息数据
    func oauthLoadUserInfo(userAccont:YHUserAccount,success: (response:AnyObject?) -> (), failure: (error:NSError) -> ()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let param = [
            "access_token":userAccont.access_token!,
            "uid":userAccont.uid!
        ]
        
        self.requset(MethodType.GET, urlString: urlString, parameters: param, success: success, failure: failure)
    }
    
}

//请求首页数据
extension YHNetworkTools{
    
    func homeLoadStatusData(sinceId:Int64, maxId:Int64, success:(response:AnyObject?)->(),failure:(error:NSError)->()){
        //url
        let url:String = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let params = [
            "access_token": YHUserAccountTools.sharedTools.accessToken!,
            "since_id":"\(sinceId)",
            "max_id":"\(maxId)"
        ]
        
        request(.GET, urlString: url, parameters: params, success: success, failure: failure)
    }
}


extension YHNetworkTools{
    //发布文字微博的请求
    func composeUpdate(status: String, success:(response:AnyObject?)->(),failure:(error:NSError)->()){
        
        //请求url
        let url = "https://api.weibo.com/2/statuses/update.json"
        //参数
        let params = [
            "access_token": YHUserAccountTools.sharedTools.accessToken!,
            "status": status
        ]
        
        request(.POST, urlString: url, parameters: params, success: success, failure: failure)
    }
    
    //发送带有图片的微博
    func comoposeUpload(status:String, imageList:[UIImage], success:(response: AnyObject?)->(), failure:(error:NSError)->()){
        
        // 请求url
        let URLString = "https://upload.api.weibo.com/2/statuses/upload.json"
        // 请求参数
        let params = [
            "access_token":YHUserAccountTools.sharedTools.accessToken!,
            "status":status
            ]
        
        
        POST(URLString, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
            
            /*
                以表单形式提交
            data:将要上传服务器的二进制文件
            name:服务器要求规定好的文件名称（协议）
            fileName: 上传文件完成后保存到服务器的文件路径 (新浪微博不需要你指定)
            mineType: 指定上传的二进制文件的格式 application/octet-stream 表示忽略上传文件的格式
            */
            
            //遍历数组
            for image in imageList{
                //image转二进制
                let data = UIImagePNGRepresentation(image)!
                
                formData.appendPartWithFileData(data, name: "pic", fileName: "oooo", mimeType: "application/octet-stream")
            }
            
            }, progress: nil, success: { (_, response) -> Void in
                success(response: response)
            }) { (_, error) -> Void in
                failure(error: error)
        }
    }
}









